<template>
  <el-dialog
    :model-value="dialogVisible"
    :title="`[ ${currentDeptName} ]部门成员`"
    width="65%"
    align-center
    @closed="handleClose"
  >
    <el-button-group>
      <el-button type="primary" :icon="CirclePlus" @click="handleOpenDialogUser">添加部门成员</el-button>
      <el-button type="danger" :icon="Remove" @click="handleRemoveUsers">移除部门成员</el-button>
      <el-button type="primary" :icon="Refresh" @click="handleRefreshSeq">更新成员序号</el-button>
    </el-button-group>
    <x-table
      ref="refTable"
      name="部门成员"
      :height="tableHeight"
      :columns="columns"
      :init-sort="{ seq: 'ascending' }"
      :data="tableData.resp.list"
      :total="tableData.resp.total"
      :loading="tableData.loading"
      @query="handleQuery"
    >
      <template #column-seq="scope">
        <el-link v-show="scope.row.userId != stateEditId" type="primary" @click="handleEdit(scope.row)">
          {{ scope.data }}
        </el-link>
        <el-input
          v-show="scope.row.userId == stateEditId"
          v-model="stateEditSeq"
          type="number"
          size="small"
          @keyup.enter="handleSaveSeq(scope.row)"
        >
          <template #append>
            <div class="icon-wrap">
              <el-icon @click="handleSaveSeq(scope.row)"><Check /></el-icon>
              <el-divider direction="vertical" />
              <el-icon @click="handleCancelSeq"><Close /></el-icon>
            </div>
          </template>
        </el-input>
      </template>
    </x-table>
    <DialogUser
      ref="refDialogUser"
      v-model:visible="dialogUserVisible"
      :api="dialogUserApi"
      @ok="handleSelectedUsers"
    />
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, nextTick } from 'vue'
import { ElMessage, ElLink, ElDialog, ElInput, ElDivider } from 'element-plus'
import { CirclePlus, Remove, Check, Close, Refresh } from '@element-plus/icons-vue'
import { confirm, util } from '@/utils'
import type { User } from '@/api/modules/system/user'
import { useUser } from '@/views/system/user/hook'
import { deptApi } from '@/api/modules/system/dept'
import type { Dept } from '@/api/modules/system/dept'
import type { DeptUser } from '@/api/modules/system/dept'
import DialogUser from '@/views/system/user/DialogList.vue'

const props = withDefaults(defineProps<{ visible: boolean }>(), {
  visible: false
})
const emits = defineEmits(['update', 'update:visible'])

const dialogVisible = computed(() => props.visible)
const tableHeight = computed(() => util.getAppHeight() * 0.55)

const currentDeptId = ref('')
const currentDeptName = ref('')
const setDept = (dept: Dept) => {
  currentDeptId.value = dept.deptId
  currentDeptName.value = dept.deptName
  nextTick(() => {
    refTable.value.refresh()
  })
}

const deptUserApi = (page: AxiosType.Pagination) => {
  return deptApi.findUserListPage(page, { deptId: currentDeptId.value })
}
const { refTable, tableData, handleQuery, filters, handleFormatter } = useUser(deptUserApi)
const columns: any[] = [
  { prop: 'userName', label: '姓名', width: 110, fixed: true },
  { prop: 'userCode', label: '编号', width: 110 },
  { prop: 'loginName', label: '账号', width: 110 },
  { prop: 'seq', label: '序号', width: 130 },
  { prop: 'cellphone', label: '手机号码', width: 130 },
  { prop: 'email', label: '邮箱地址', width: 140 },
  { prop: 'gender', label: '性别', formatter: handleFormatter, filters: filters.gender }
]

// 添加用户
const dialogUserVisible = ref(false)
const refDialogUser = ref()
const dialogUserApi = (page: AxiosType.Pagination) => {
  return deptApi.findUserListPage(page, { deptId: currentDeptId.value, exclude: true })
}
const handleOpenDialogUser = () => {
  dialogUserVisible.value = true
  refDialogUser.value.refresh()
}
const handleSelectedUsers = ({ users }: any) => {
  const userIds = users.map((user: User) => {
    return user.userId
  })
  deptApi.addDeptUser({ deptId: currentDeptId.value, userIds } as DeptUser).then(resp => {
    if (resp.success) {
      refTable.value.refresh()
      ElMessage.success(`${userIds.length} 个用户被添加`)
      emits('update')
    } else {
      ElMessage.error(resp.message)
    }
  })
}
const handleRemoveUsers = () => {
  if (refTable.value.selection.length === 0) {
    ElMessage.warning({ message: '请至少勾选列表中的一条数据' })
    return
  }
  confirm('确定要移除用户吗?', () => {
    const userIds = refTable.value.selection.map((item: User) => {
      return item.userId
    })
    deptApi.removeDeptUser({ deptId: currentDeptId.value, userIds } as DeptUser).then(resp => {
      if (resp.success) {
        refTable.value.refresh()
        ElMessage.success(`${userIds.length} 个用户被移除`)
        emits('update')
      } else {
        ElMessage.error(resp.message)
      }
    })
  })
}

const stateEditId = ref()
const stateEditSeq = ref(0)
const handleEdit = (row: any) => {
  stateEditId.value = row.userId
  stateEditSeq.value = row.seq
}
const handleSaveSeq = (row: any) => {
  deptApi.updateUserSeq({ deptId: row.deptId, userId: row.userId, seq: stateEditSeq.value }).then(resp => {
    if (resp.success) {
      row.seq = stateEditSeq.value
      ElMessage.success(`${row.userName} 排序已更新`)
    } else {
      ElMessage.error(resp.message)
    }
  })
  stateEditId.value = ''
}
const handleCancelSeq = () => {
  stateEditId.value = ''
}

const handleClose = () => {
  emits('update:visible', false)
}

const handleRefreshSeq = () => {
  deptApi.refreshUserSeq(currentDeptId.value).then(resp => {
    if (resp.success) {
      refTable.value.refresh()
      ElMessage.success(`部门成员序号已更新`)
    } else {
      ElMessage.error(resp.message)
    }
  })
}
defineExpose({ setDept })
</script>

<style lang="scss" scoped>
:deep(.el-input-group__append) {
  padding: 0;
}
.icon-wrap {
  display: flex;
  justify-content: center;
  width: 55px;
  cursor: pointer;
}
</style>
